import UIKit

extension UIColor {
    
    /// Initialize a UIColor with a hex string (e.g. "#FFFFFF" or "FFFFFF")
    /// - Parameter hexString: The hex string, with or without the '#' prefix
    convenience init?(hexString: String) {
        // Remove the '#' prefix if it exists
        let hex = hexString.hasPrefix("#") ? String(hexString.dropFirst()) : hexString
        
        // Ensure the hex string has a valid length (6 or 8 characters)
        guard hex.count == 6 || hex.count == 8 else {
            return nil
        }
        
        // Convert the hex string to an integer
        var rgbValue: UInt64 = 0
        Scanner(string: hex).scanHexInt64(&rgbValue)
        
        // Extract the color components
        if hex.count == 6 {
            // RGB format (without alpha)
            self.init(
                red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                alpha: 1.0
            )
        } else {
            // RGBA format (with alpha)
            self.init(
                red: CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0,
                green: CGFloat((rgbValue & 0x00FF0000) >> 16) / 255.0,
                blue: CGFloat((rgbValue & 0x0000FF00) >> 8) / 255.0,
                alpha: CGFloat(rgbValue & 0x000000FF) / 255.0
            )
        }
    }
    
    /// Create a UIColor from a hex string
    /// - Parameter hexString: The hex string, with or without the '#' prefix
    /// - Returns: A UIColor instance or nil if the string is invalid
    static func fromHex(_ hexString: String) -> UIColor? {
        return UIColor(hexString: hexString)
    }
}
